|
1
|
|
|
import {CommandHandler} from '@nestjs/cqrs'; |
|
2
|
|
|
import {Inject} from '@nestjs/common'; |
|
3
|
|
|
import {UpdateCustomerCommand} from './UpdateCustomerCommand'; |
|
4
|
|
|
import {ICustomerRepository} from 'src/Domain/Customer/Repository/ICustomerRepository'; |
|
5
|
|
|
import {CustomerNotFoundException} from 'src/Domain/Customer/Exception/CustomerNotFoundException'; |
|
6
|
|
|
import {IsCustomerAlreadyExist} from 'src/Domain/Customer/Specification/IsCustomerAlreadyExist'; |
|
7
|
|
|
import {CustomerAlreadyExistException} from 'src/Domain/Customer/Exception/CustomerAlreadyExistException'; |
|
8
|
|
|
import {IAddressRepository} from 'src/Domain/Customer/Repository/IAddressRepository'; |
|
9
|
|
|
|
|
10
|
|
|
@CommandHandler(UpdateCustomerCommand) |
|
11
|
|
|
export class UpdateCustomerCommandHandler { |
|
12
|
|
|
constructor( |
|
13
|
|
|
@Inject('ICustomerRepository') |
|
14
|
|
|
private readonly customerRepository: ICustomerRepository, |
|
15
|
|
|
@Inject('IAddressRepository') |
|
16
|
|
|
private readonly addressRepository: IAddressRepository, |
|
17
|
|
|
private readonly isCustomerAlreadyExist: IsCustomerAlreadyExist |
|
18
|
|
|
) {} |
|
19
|
|
|
|
|
20
|
|
|
public async execute(command: UpdateCustomerCommand): Promise<void> { |
|
21
|
|
|
const {id, name, city, street, country, zipCode} = command; |
|
22
|
|
|
|
|
23
|
|
|
const customer = await this.customerRepository.findOneById(id); |
|
24
|
|
|
if (!customer) { |
|
25
|
|
|
throw new CustomerNotFoundException(); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
if ( |
|
29
|
|
|
name !== customer.getName() && |
|
30
|
|
|
true === (await this.isCustomerAlreadyExist.isSatisfiedBy(name)) |
|
31
|
|
|
) { |
|
32
|
|
|
throw new CustomerAlreadyExistException(); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
const address = customer.getAddress(); |
|
36
|
|
|
customer.updateName(name); |
|
37
|
|
|
address.update(street, city, zipCode, country); |
|
38
|
|
|
|
|
39
|
|
|
await Promise.all([ |
|
40
|
|
|
this.customerRepository.save(customer), |
|
41
|
|
|
this.addressRepository.save(address) |
|
42
|
|
|
]); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|